package com.cjg.netCode;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class udpChatRecevice implements Runnable {
    DatagramSocket socket =null;
    private int port;
    private String msg;

    public udpChatRecevice(int port,String msg) {
        this.port=port;
        this.msg=msg;
        //创建接收端口
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            try {
                //接收数据
                byte[] bytes = new byte[1024];
                DatagramPacket Packet = new DatagramPacket(bytes,0,bytes.length);
                socket.receive(Packet); //阻塞式 接受包

                byte[] data = Packet.getData();
                String s = new String(data, 0, data.length);
                System.out.println(msg+""+s);

                if (s.equals("bye")){

                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
